import { Injectable, EventEmitter } from '@angular/core';
import { Http, URLSearchParams } from '@angular/http';
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';




@Injectable({
  providedIn: 'root'
})

export class ProductService {
  // private products: Product[] = [
  //   new Product(1, "第一个商品", 1.99, 3.5, "这是第一个商品", ["电子产品", "硬件设备"]),
  //   new Product(2, "第二个商品", 1.99, 2, "这是第二个商品", ["图片"]),
  //   new Product(3, "第三个商品", 1.99, 3, "这是第三个商品", ["硬件设备"]),
  //   new Product(4, "第四个商品", 1.99, 4, "这是第四个商品", ["电子产品", "硬件设备"]),
  //   new Product(5, "第五个商品", 1.99, 2.5, "这是第五个商品", ["电子产品"]),
  //   new Product(6, "第六个商品", 1.99, 4.5, "这是第六个商品", ["图片"])
  // ]
  // private comments: Comment[] = [
  //   new Comment(1, 1, "2017-02-02 22:22:22", "张三", 3, "东西不错"),
  //   new Comment(2, 1, "2017-02-02 22:22:22", "张三", 3, "东西不错"),
  //   new Comment(3, 1, "2017-02-02 22:22:22", "张三", 3, "东西不错"),
  //   new Comment(4, 2, "2017-02-02 22:22:22", "张三", 3, "东西不错")
  // ]

  searchEvent: EventEmitter<ProductSearchParams> = new EventEmitter();
  constructor(private http: Http) { }
  getAllCategories(): string[] {
    return ["电子产品", "硬件设备", "图书"]
  }
  getProducts(): Observable<Product[]> {
    return this.http.get("/api/products").pipe(
      map(res => res.json())
    )
  }

  getProduct(id: number): Observable<Product> {

    return this.http.get("/api/products/" + id).pipe(
      map(res =>
        res.json()
      ))
    // return this.products.find((product) =>
    //   product.id == id
    // )
  }
  getCommentsForProductId(id: number): Observable<Comment[]> {
    // return this.comments.filter((comment: Comment) => comment.productId == id)
    return this.http.get("/api/products/" + id + "/comments").pipe(
      map(res => res.json())
    )
  }
  search(params: ProductSearchParams): Observable<Product[]> {
    return this.http.get("/api/products", { search: this.encodeParams(params) }).pipe(
      map(res => res.json())
    )
  }
  private encodeParams(params: ProductSearchParams) {

    return Object.keys(params).filter(key => params[key]).reduce((sum: URLSearchParams, key) => {
      sum.append(key, params[key])
      return sum
    }, new URLSearchParams)

  }
}
export class ProductSearchParams {
  constructor(public title: string, public price: number, public category: string) {

  }
}
export class Comment {
  constructor(
    public id: number,
    public productId: number,
    public timestamp: string,
    public user: string,
    public rating: number,
    public content: string
  ) {

  }

}
export class Product {
  constructor(
    public id: number,
    public title: string,
    public price: number,
    public rating: number,
    public desc: string,
    public categoryes: Array<string>
  ) { }
}